package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.Voucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.print.DocFlavor;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//import static com.hmdp.utils.RedisConstants.SECKILL_USERSET_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ISeckillVoucherService seckillVoucherService;

    @Autowired
    private RedisIdWorker redisIdWorker;

    @Autowired
    private RedissonClient redissonClient;

    private static  final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    @PostConstruct
    private void init(){
//        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    private class VoucherOrderHandler implements  Runnable{

        String queueName = "stream.orders" ;
        @Override
        public void run() {
            while(true){
                try {
                    // 1.创建消费组 XGROUP CREATE stream.orders g1 >
//                stringRedisTemplate.opsForStream().createGroup(queueName, ReadOffset.lastConsumed(),"g1");


                    // 已经创建了stream.order的队列，但是没有 消费组group 还有消费者
                    // 2.获取消息队列中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS stream.order >
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed())
                    );

                    // 3. 判断信息是否为空
                    if(list == null || list.isEmpty()){
                        Thread.sleep(1000000000);
                        continue;
                    }

                    // 4 解析数据
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);

                    //5 创建订单
                    createVoucherOrder(voucherOrder);

                    //6.确认信息 XACK
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());
                } catch (Exception e) {
                    log.error("处理订单出现了异常",e);

                    //发生了异常再次进行处理
//                    handlePendingList();
                }
            }
        }


        // 当上述逻辑出现错误后
        private void handlePendingList(){
            while(true){
                try {
                    // 1.创建消费组 XGROUP CREATE stream.orders g1 >
//                stringRedisTemplate.opsForStream().createGroup("stream.orders", ReadOffset.lastConsumed(),"g1");

                    // 2.获取消息队列中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 STREAMS stream.order 0
                    // 从pendinglist中读取文件需要进行 阻塞
                    // 0 代表的就是从pendingList中读取文件
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            // 这一步就是定义消费者
                            Consumer.from("g1", "c1"),
                            // 每次读取一个元素并且阻塞两秒
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create(queueName,ReadOffset.from("0")));

                    // 3. 判断信息是否为空
                    if(list == null || list.isEmpty()){
                        // 说明在pendingList中没有异常消息需要我们进行处理
                        break;
                    }

                    // 4 解析数据
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);

                    //5 创建订单
                    createVoucherOrder(voucherOrder);

                    //6.确认信息 XACK
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());
                } catch (Exception e) {
                    log.error("处理pendList出现了异常",e);

                }
            }

        }
    }

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(long.class);
    }


//    @Autowired
//    private
@Override
//@Transactional
public Result seckillVoucher(Long voucherId) {
    Long userId = UserHolder.getUser().getId();
    Long orderId = redisIdWorker.nextId("order");
    Long result = stringRedisTemplate.execute(
            SECKILL_SCRIPT, Collections.emptyList(), voucherId.toString(), userId.toString(), orderId.toString()
    );

    if(result!=0){
        return Result.fail(result == 1 ? "库存不足":"不能重复下单");
    }

    // TODO 保存到阻塞队列，开启异步线程进行运作
    // 但是由于我们是异步进行处理的，加入消息队列后，那么前后端交互的线程就结束了
    return Result.ok(orderId);

}


    public synchronized void createVoucherOrder(VoucherOrder voucherOrder) {


        Long userId = UserHolder.getUser().getId();
        // 5.1.查询订单
        int count = query().eq("user_id", userId).eq("voucher_id", voucherOrder.getVoucherId()).count();
        // 5.2.判断是否存在
        if (count > 0) {
            // 用户已经购买过了
            log.error("用户已经购买过一次");
        }

        // 6.扣减库存
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1") // set stock = stock - 1
                .eq("voucher_id", voucherOrder.getVoucherId()).gt("stock", 0) // where id = ? and stock > 0
                .update();
        if (!success) {
            // 扣减失败
           log.error("库存不足");
           return ;
        }


        // 真正的进行下单
        save(voucherOrder);
        // 把已经下单的用户保存到redis中，便于后面的判断运行
//        stringRedisTemplate.opsForSet().add(SECKILL_USERSET_KEY,(UserHolder.getUser().getId()).toString());

    }
}
